//
//  KABModifyPwdVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/1/17.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABModifyPwdVC.h"
#import <UINavigationBar+Awesome.h>
#import "XDAFNetworking.h"
#import "XDRsa.h"
#import "MBProgressHUD+XDPrompt.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "KABModel.h"
#import "ApiManager.h"

@interface KABModifyPwdVC ()

@property (weak, nonatomic) IBOutlet UITextField *pwdOldTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdNew1TextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdNew2TextField;
@property (weak, nonatomic) IBOutlet UIButton *modifyPwdBtn;

@end

@implementation KABModifyPwdVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"修改密码";
}

- (void)initSubViews {
    NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:KABGlobalColorLoginFontColor],
                          NSFontAttributeName : [UIFont systemFontOfSize:14]};
    self.pwdOldTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"原始密码" attributes:dic];
    self.pwdNew1TextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"新密码" attributes:dic];
    self.pwdNew2TextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"再次输入新密码" attributes:dic];
    
    self.modifyPwdBtn.layer.masksToBounds = YES;
    self.modifyPwdBtn.layer.cornerRadius = CGRectGetHeight(self.modifyPwdBtn.frame) / 2.0;
    [self.modifyPwdBtn addTarget:self action:@selector(modifyPwdBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar lt_reset];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - delegate
#pragma mark - event response
- (void)modifyPwdBtnTapped:(UIButton *)btn {
    if (![self checkUserInput]) {
        return;
    }
    
    [self requestModifyPassword];
}

#pragma mark - private methods
- (BOOL)checkUserInput {
    if (!self.pwdOldTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入手机号"];
        return NO;
    }
    
    if (self.pwdNew1TextField.text.length < KABGlobalPwdMinLength
        || self.pwdNew1TextField.text.length > KABGlobalPwdMaxLength) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"密码长度为6-20位"];
        return NO;
    }
    
    if (![self.pwdNew2TextField.text isEqualToString:self.pwdNew1TextField.text]) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"两次输入的密码不一致"];
        return NO;
    }
    
    return YES;
}

- (void)backToSuperView {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestModifyPassword {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSInteger timestramp = [[NSDate date] timeIntervalSince1970];
    NSDictionary *dic = @{@"password" : self.pwdOldTextField.text,
                          @"timestamp": @(timestramp)};
    NSString *tokenOld = [XDRsa base64EncryptWithDictionary:dic];
    
    NSDictionary *dicNew = @{@"password" : self.pwdNew1TextField.text,
                             @"timestamp": @(timestramp)};
    NSString *tokenNew = [XDRsa base64EncryptWithDictionary:dicNew];
    
    NSDictionary *parameters = @{@"account"  : [KABModel sharedInstance].userInfo.account,
                                 @"old_token": tokenOld,
                                 @"new_token": tokenNew,
                                 @"access_token": [KABModel sharedInstance].userInfo.access_token};
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiModifyPassword] parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"修改密码返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            // 更新Token
            [[KABModel sharedInstance] updateTokenByModifyPwd:responseObject];
            [[KABModel sharedInstance] saveUserInfoWithPwd:self.pwdNew1TextField.text];
            MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"修改密码成功"];
            hud.completionBlock = ^(){
                [self backToSuperView];
            };
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"修改密码失败：%@", error.localizedDescription);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}
#pragma mark - getters and setters

@end
